package cn.com.yahoo.ma.tingqiang.alarm;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import cn.com.yahoo.ma.tingqiang.alarm.util.Constant;

public class AlarmList implements Serializable {
	private List<Alarm> stores = new ArrayList<Alarm>();

	public final List<Alarm> getAlarms() {
		cleanAlarms(); // delete the alarms passed
		Collections.sort(stores);
		return stores;
	}

	@Override
	public String toString() {
		StringBuilder objectInfo = new StringBuilder();
		for (Alarm alarm : stores) {
			objectInfo.append(alarm);
			objectInfo.append(Constant.NEWLINE);
		}
		return objectInfo.toString();
	}

	private void cleanAlarms() {
		Date date = new Date();
		long dateValue = date.getTime();

		List<Alarm> shouldBeDeleted = new ArrayList<Alarm>();

		for (Alarm alarm : stores) {
			if (alarm.getTimeValue() < dateValue + Constant.OPERATION_TIME) {
				shouldBeDeleted.add(alarm);
			}
		}
		stores.removeAll(shouldBeDeleted);
	}

	public final void addAlarm(final Alarm alarm) {
		stores.add(alarm);
	}

	public void clearAll() {
		this.stores.clear();
	}

	public static void save(final String saveFileName, final AlarmList alarmList)
			throws FileNotFoundException, IOException {
		ObjectOutputStream output = null;
		try {
			output = new ObjectOutputStream(new FileOutputStream(saveFileName));
			output.writeObject(alarmList);
		} finally {
			output.close();
		}

	}

	public static AlarmList restore(final String saveFileName) {
		ObjectInputStream input = null;

		try {
			input = new ObjectInputStream(new FileInputStream(saveFileName));
			AlarmList alarmList = (AlarmList) input.readObject();
			input.close();
			return alarmList;
		} catch (Exception e) {
			return null;
		}
	}
}
